package cn.piggy.gateway.core.proxy.cglib;

import cn.piggy.gateway.core.proxy.MyGenericReference;
import cn.piggy.gateway.core.session.GatewaySession;
import java.util.HashMap;
import java.util.Map;


public class MapperProxyFactoryManager {

    public MapperProxyFactoryManager() {}

    // 泛化调用静态代理工厂
    private final Map<String, MapperProxyFactory> knownMappers = new HashMap<>();

    public MyGenericReference getProxyObject(String uri, GatewaySession gatewaySession) {
        MapperProxyFactory mapperProxyFactory = knownMappers.get(uri);
        if (mapperProxyFactory == null) {
            throw new RuntimeException("Uri " + uri + " is not known to the MapperRegistry.");
        }
        try {
            return mapperProxyFactory.newInstance(gatewaySession);
        } catch (Exception e) {
            throw new RuntimeException("Error getting mapper instance. Cause: " + e, e);
        }
    }

    public void produceFactory(String uri) {
        knownMappers.put(uri, new MapperProxyFactory(uri));
    }

    public void destructionFactory(String uri) {
        knownMappers.remove(uri);
    }

    public boolean isExist(String uri) {
        return knownMappers.containsKey(uri);
    }

}
